package com.smy.maven.plugin;

import com.itextpdf.text.DocumentException;
import com.smy.tool.api.domain.SmyApiServiceInfo;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;

/**
 * Description:
 *
 * @author 
 * @since 2017/11/30.
 */
@Mojo(name = "generator", requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME)
public class GeneratorApiDoc extends AbstractMojo {

    @Parameter(defaultValue = "1", required = true)
    private Integer fileType;

    @Parameter
    private String packageName;

    @Parameter
    private String serviceNames;

    @Parameter(defaultValue = "接口文档", required = true)
    private String docTitle;

    @Parameter(defaultValue = "./", required = true)
    private String docDir;

    @Parameter(defaultValue = "${project}")
    private MavenProject project;

    private ClassLoader getClassLoader() throws MojoExecutionException {
        try {
            List<String> classpathElements = project.getCompileClasspathElements();
            classpathElements.addAll(project.getRuntimeClasspathElements());
            classpathElements.add(project.getBuild().getOutputDirectory());
            URL[] urls = new URL[classpathElements.size()];
            for (int i = 0; i < classpathElements.size(); ++i) {
                urls[i] = new File(classpathElements.get(i)).toURI().toURL();

            }
            return new URLClassLoader(urls, getClass().getClassLoader());
        } catch (Exception e) {
            throw new MojoExecutionException("Couldn't create a classloader.", e);
        }
    }

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        getLog().info("开始生成Api文档:" + docTitle + ".pdf");
        ReadApiInfo readApiDoc = null;
        if (fileType == 1) {
            readApiDoc = new ReadApiInfo(this.getClassLoader(), packageName);
        } else {
            readApiDoc = new ReadApiInfo(this.getClassLoader(), serviceNames.split(","));
        }
        List<SmyApiServiceInfo> serviceInfoList = readApiDoc.loadApiInfo();
        ReportApiPdf reportApiPdf = new ReportApiPdf(docTitle, docDir, serviceInfoList);
        try {
            reportApiPdf.reportPdf();
        } catch (IOException e) {
            getLog().error("生成PDF异常.", e);
        } catch (DocumentException e) {
            getLog().error("生成PDF异常.", e);
        }

    }
}
